package com.wujilin.okra.fragment;

import static com.wujilin.okra.Okra.EXTRA_LOADER_ID;
import static com.wujilin.okra.Okra.EXTRA_OBJECTIVE_QUARTER;
import static com.wujilin.okra.Okra.EXTRA_OBJECTIVE_YEAR;
import static com.wujilin.okra.Okra.EXTRA_OKR_LIST_TITLE;
import static com.wujilin.okra.Okra.LOADER_ARCHIVE_LIST;
import static com.wujilin.okra.Okra.LOADER_OKRA_LIST_BY_QUARTER;
import static com.wujilin.okra.Okra.LOADER_OKRA_LIST_BY_YEAR;
import android.app.Activity;
import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.wujilin.okra.R;
import com.wujilin.okra.adapter.ArchiveListAdapter;
import com.wujilin.okra.database.ModelCursor;
import com.wujilin.okra.loader.QueryCursorLoader;

/**
 * @author Belin Wu
 */
public class ArchiveListFragment extends ListFragment implements LoaderCallbacks<Cursor> {
	private Callback callback;
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		callback = (Callback) activity;
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLoaderManager().initLoader(LOADER_ARCHIVE_LIST, null, this);
    }
    
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
    	TextView titleText = (TextView) v.findViewById(R.id.archive_title);
    	int year = (int) (id / 10);
    	int quarter = (int) (id % 10);
    	
    	Intent intent = new Intent();
    	intent.putExtra(EXTRA_OBJECTIVE_YEAR, year);
    	intent.putExtra(EXTRA_OBJECTIVE_QUARTER, quarter);
    	intent.putExtra(EXTRA_OKR_LIST_TITLE, titleText.getText().toString());
    	intent.putExtra(EXTRA_LOADER_ID, quarter == 0 ? LOADER_OKRA_LIST_BY_YEAR : LOADER_OKRA_LIST_BY_QUARTER);
    	
    	callback.onViewOkraList(intent);
    }
    
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		String sql = "select year||quarter _id, year||'/Q'||quarter title, year, quarter, count(*) count from objective group by year, quarter union select year||0 _id, year title, year, 0 quarter, count(*) count from objective group by year order by year desc, quarter asc";
		return new QueryCursorLoader(getActivity(), sql);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		ListAdapter adapter = new ArchiveListAdapter(getActivity(), (ModelCursor) data);
		setListAdapter(adapter);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		setListAdapter(null);
	}
	
	public static interface Callback {
		void onViewOkraList(Intent intent);
	}
}
